package com.easy.lab.shixun.controller.ws;

import com.easy.lab.shixun.common.constant.MessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;


/**
 * ws核心配置
 * @Author: https://gitee.com/wesleyOne
 * @Date: 12.07 2019
 */
@Configuration
@EnableWebSocketMessageBroker
public class SimpleWebSocketMessageBrokerConfigurer implements WebSocketMessageBrokerConfigurer {

    @Autowired
    private SimpleWebSocketHandlerDecoratorFactory webSocketHandlerDecoratorFactory;

    @Autowired
    private SimplePrincipalHandshakeHandler principalHandshakeHandler;

    @Autowired
    private SimpleHandshakeInterceptor handshakeInterceptor;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册该路径使用Stomp协议
        registry.addEndpoint(MessageConstant.STOMP_ENDPOINT)
                .setAllowedOrigins("*")
                .setHandshakeHandler(principalHandshakeHandler)
                .addInterceptors(handshakeInterceptor)
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 启动点对点和广播
        registry.enableSimpleBroker(MessageConstant.BROKER_QUEUE, MessageConstant.BROKER_TOPIC);
        // 设置点对点的路由前缀
        registry.setUserDestinationPrefix(MessageConstant.BROKER_QUEUE_PREFIX);
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        registration.addDecoratorFactory(webSocketHandlerDecoratorFactory);
    }

}
